//
//  WYCPersonalCenterController.m
//  51信用卡
//
//  Created by 中企互联 on 2017/11/4.
//  Copyright © 2017年 中企互联. All rights reserved.
//

#import "WYCPersonalCenterController.h"
#import "WYCMePhotoModel.h"

@interface WYCPersonalCenterController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

/** 遮盖View*/
@property(nonatomic,strong)UIView * coverView;

/** 模型*/
@property(nonatomic,strong)WYCMePhotoModel * MePhotoModel;
/** 显示View*/
@property(nonatomic,strong)UIView * showView;


/** 表视图*/
@property(nonatomic,strong)UITableView * tableView;


/** 头像*/
@property(nonatomic,strong)UIImageView * photoImage;


/**
 *头像
 */
@property (nonatomic,strong)UIImageView * saveimageView;


@end

@implementation WYCPersonalCenterController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    //Nav
    
    
    
    //表视图创建
    [self setupTableView];
    
    
    [self setupRequster];
    
    
    
    
    
}
- (void)setupRequster{
    
    NSString * str = [NSString stringWithFormat:@"%@token=%@",userPortraitDetail,[WYCAccountTool unarchivetoken]];
    [HttpTool POST:str params:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([[responseObject objectForKey:@"code"] intValue] == 0) {
            NSDictionary * dict = responseObject[@"result"];
            self.MePhotoModel = [WYCMePhotoModel mj_objectWithKeyValues:dict];
            if (self.MePhotoModel.imgUrl.length == 0){
                self.photoImage.image = [UIImage imageNamed:@"51logo"];
                
            }else{
                [self.photoImage sd_setImageWithURL:[NSURL URLWithString:self.MePhotoModel.imgUrl]];
            }
        }else{
            [self showToast:msgStr];
            
        }
        [self setupNav];
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}
#pragma make --------->>表视图创建
- (void)setupTableView
{
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NavHeight, ScreenWidth, WYCcellHeight * 4 - 80* px) style:UITableViewStylePlain];
    //    self.tableView.backgroundColor = [UIColor redColor];
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = NO;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
}
#pragma make --------->>setupNav
- (void)setupNav{
    
    self.view.backgroundColor = WYCGlobalBg;
    self.navigationItem.title = @"个人信息";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    [self.navigationController.navigationBar setBarTintColor:WYCMain];
    
}

#pragma make -------->>数据代理  数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 3;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 240 * px;
    }else{
        return WYCcellHeight;
    }
    
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    tableView.tableFooterView = [[UIView alloc] init];
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"123"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"123"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    CGFloat cellXY = 40 * px;
    
    CGFloat celltitle = 80 * px;
    
    if (indexPath.row == 0) {
        UIView * cellView = [[UIView alloc] init];
        cellView.frame = CGRectMake(0, 0, ScreenWidth, WYCcellHeight);
        [cell addSubview:cellView];
        
        
        UILabel * photoLabel = [[UILabel alloc] init];
        photoLabel.frame = CGRectMake(cellXY, 0, 150 * px, 240 * px);
        photoLabel.text = @"头像";
        photoLabel.font = [UIFont systemFontOfSize:MiddleFont];
        [cellView addSubview:photoLabel];
        
        
        UIImageView * photoImageView = [[UIImageView alloc] init];
        photoImageView.frame = CGRectMake(cellView.width - celltitle - 200 * px, 20 * px, 200 * px, 200 * px);
        photoImageView.backgroundColor = [UIColor whiteColor];
        WYCLog(@"%@",self.MePhotoModel.imgUrl);
        [photoImageView sd_setImageWithURL:[NSURL URLWithString:self.MePhotoModel.imgUrl]];
        photoImageView.layer.masksToBounds = YES;
        [photoImageView setUserInteractionEnabled:YES];
        [photoImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showPictureClick)]];
        photoImageView.layer.cornerRadius = photoImageView.width / 2;
        [cellView addSubview:photoImageView];
        self.photoImage = photoImageView;
        
    }
    else if (indexPath.row == 1){
        UIView * cellView = [[UIView alloc] init];
        cellView.frame = CGRectMake(0, 0, ScreenWidth, WYCcellHeight);
        [cell addSubview:cellView];
        
        
        UILabel * nameLabel = [[UILabel alloc] init];
        nameLabel.frame = CGRectMake(cellXY, cellXY, 150 * px, celltitle);
        nameLabel.text = @"姓名";
        nameLabel.font = [UIFont systemFontOfSize:MiddleFont];
        [cellView addSubview:nameLabel];
        
        
        UILabel * name = [[UILabel alloc] init];
        name.frame = CGRectMake(CGRectGetMaxX(nameLabel.frame), cellXY, cellView.width - nameLabel.width * 2, celltitle);
        name.textAlignment = NSTextAlignmentRight;
        name.textColor = [UIColor blackColor];
        name.text = [WYCAccountTool unarchiveuserName];
        name.font = [UIFont systemFontOfSize:MiddleFont];
        [cellView addSubview:name];
        
    }else{
        UIView * cellView = [[UIView alloc] init];
        cellView.frame = CGRectMake(0, 0, ScreenWidth, WYCcellHeight);
        [cell addSubview:cellView];
        
        
        UILabel * nameLabel = [[UILabel alloc] init];
        nameLabel.frame = CGRectMake(cellXY, cellXY, 150 * px, celltitle);
        nameLabel.text = @"手机";
        nameLabel.font = [UIFont systemFontOfSize:MiddleFont];
        [cellView addSubview:nameLabel];
        
        UILabel * name = [[UILabel alloc] init];
        name.frame = CGRectMake(CGRectGetMaxX(nameLabel.frame), cellXY, cellView.width - nameLabel.width * 2, celltitle);
        name.textAlignment = NSTextAlignmentRight;
        name.textColor = [UIColor blackColor];
        name.text = [WYCAccountTool unarchivemobile];
        name.font = [UIFont systemFontOfSize:MiddleFont];
        [cellView addSubview:name];
        
    }
    return cell;
}
#pragma make -------->>保存
- (void)addClick{
    WYCLogFunc;
    [self request];
    
}

#pragma make --------->>修改头像
- (void)showPictureClick{
    WYCLogFunc;

    
    
    UIAlertController *aler=[UIAlertController alertControllerWithTitle:@"更换头像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //从相机选取
    UIAlertAction *album=[UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *picker=[[UIImagePickerController alloc]init];
        picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
        picker.mediaTypes=[UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
        picker.allowsEditing=YES;
        picker.delegate=self;
        [self presentViewController:picker animated:YES completion:nil];
    }];
    
    //从相机选取
    UIAlertAction *camera=[UIAlertAction actionWithTitle:@"相机拍摄" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.mediaTypes =[UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
        picker.allowsEditing = YES;
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:nil];
        
    }];
    
    UIAlertAction *cancl=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [aler addAction:cancl];
    [aler addAction:album];
    [aler addAction:camera];
    [self presentViewController:aler animated:YES completion:nil];
    
}
//选取图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    
    UIImage *image1=[info objectForKey:UIImagePickerControllerEditedImage];
//    self.saveimageView.image = image1;
    self.photoImage.image = image1;
   
    //选取完图片之后关闭视图
    [self dismissViewControllerAnimated:YES completion:nil];
    
    
}
- (void)request{
    
    NSData * data = UIImageJPEGRepresentation(self.photoImage.image, 0.0000001);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
//    NSString * str = [NSString stringWithFormat:@"%@token=%@&base64Img=%@",saveUserPortrait,[WYCAccountTool unarchivetoken],encodedImageStr];
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"token"] = [WYCAccountTool unarchivetoken];
    params[@"base64Img"] = encodedImageStr;
    [HttpTool POST:saveUserPortrait params:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([[responseObject objectForKey:@"code"] intValue] == 0) {
            
            [self showToast:msgStr];
            [self.navigationController popViewControllerAnimated:YES];
            
        }else{
            
            [self showToast:msgStr];
            
        }
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        [self showToast:Failed];
    }];
}

   
    
- (void)viewWillAppear:(BOOL)animated{
    
     [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    
        UIView * NavView = [[UIView alloc] init];
        NavView.frame = CGRectMake(0, 0, ScreenWidth, NavHeight);
        NavView.backgroundColor = WYCmainColor;
        [self.view addSubview:NavView];
    
    
    
        CALayer *bottomLineLayer = [[CALayer alloc] init];
        bottomLineLayer.frame = CGRectMake(0, NavView.bounds.size.height - 0.5, NavView.bounds.size.width, 0.5);
        bottomLineLayer.backgroundColor = WYCmainColor.CGColor;
        [NavView.layer addSublayer:bottomLineLayer];
    
    
        //返回按钮
        UIButton *  backbutton = [[UIButton alloc] init];
//        [backbutton setImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
        [backbutton setTitle:@"保存" forState:UIControlStateNormal];
        [backbutton addTarget:self action:@selector(addClick) forControlEvents:UIControlEventTouchUpInside];
        backbutton.frame = CGRectMake(NavView.width - 226 * px, titleY, 200 * px , 68 * px);
        backbutton.titleLabel.font = [UIFont systemFontOfSize:BigFont];
        backbutton.contentHorizontalAlignment= UIControlContentHorizontalAlignmentRight;
        [NavView addSubview:backbutton];
    
    
        //返回按钮
        UIButton *  fanhuibutton = [[UIButton alloc] init];
        [fanhuibutton setImage:[UIImage imageNamed:@"Nav_back"] forState:UIControlStateNormal];
        [fanhuibutton addTarget:self action:@selector(photoClick) forControlEvents:UIControlEventTouchUpInside];
        fanhuibutton.frame = CGRectMake(30 * px, titleY, 66 * px , 66 * px);
        [NavView addSubview:fanhuibutton];
    
    
        UILabel * NavRigsterLabel = [[UILabel alloc] init];
        NavRigsterLabel.frame = CGRectMake(0, titleY, NavView.width, 68 * px);
        NavRigsterLabel.textColor = [UIColor whiteColor];
        NavRigsterLabel.font = [UIFont boldSystemFontOfSize:BigFont];
        NavRigsterLabel.textAlignment = NSTextAlignmentCenter;
        NavRigsterLabel.text = @"个人信息";
        [NavView addSubview:NavRigsterLabel];
}

- (void)photoClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}
@end

